<script setup lang="tsx">
defineOptions({
  name: "FULLSCREEN_GAS_OPERATION_OVERVIEW"
});

import { ref, onMounted, onUnmounted, nextTick, computed } from "vue";
import safeDays from "@/views/electricity/operation/overview/components/safeDays.vue";
import {
  queryDeviceStatistics,
  queryPlatformOverview,
  queryBulkGasConsumptionStat,
  queryConsumptionAnalysis,
  queryGasNameList,
  getSafeDays,
  updateSafeDays,
  queryDetectorStatusStat,
  queryDetectorIsolationTasks,
  queryAcidBucketTaskStat,
  queryGasCylinderStatusStat,
  queryGasCylinderTaskStat,
  queryTankTaskStat,
  queryAcidBucketStatusStat,
  querySpcExceedStat
} from "@/api/modules/operation";
import { queryDictData } from "@/api/common";
import { useLabelLayoutRingGraphFn, useLabelLayoutBarChartFn, useGetBarChartsAgOptions, useGetRingGraphAgOptions } from "@/hooks/useEcharts";
import echartsCom from "@/views/common/components/echartsCom/index.vue";
import echartsChart from "@/views/common/components/echartsChart/index.vue";
import deviceStatisticsTasks from "./components/deviceStatisticsTasks.vue";
import modelBox from "@/views/common/components/modelBox/index.vue";
import gasBoardBulkGasStatis from "./components/gasBoardBulkGasStatis.vue";
import gasBoardSpecialGasStatis from "./components/gasBoardSpecialGasStatis.vue";
import gasBoardChemicalsStatis from "./components/gasBoardChemicalsStatis.vue";
import gasBoardSPCStatis from "./components/gasBoardSPCStatis.vue";
import gasBoardShiftTable from "./components/gasBoardShiftTable.vue";
import { deviceStatus } from "@/utils/constant";
import { useFullscreen, useTransition, TransitionPresets, useElementSize } from "@vueuse/core";
import dayjs from "dayjs";
import topBoard from "@/views/common/topBoard/index.vue";

const deviceStatusMap = ref<Map<string, Record<string, any>>>(new Map());

const gasOverviewRef = ref<HTMLElement>(null);
// 大宗气耗量统计
const gasBoardBulkGasStatisRef = ref<InstanceType<typeof gasBoardBulkGasStatis> | null>(null);
// 特气耗量统计
const gasBoardSpecialGasStatisRef = ref<InstanceType<typeof gasBoardSpecialGasStatis> | null>(null);
// 化学品耗量统计
const gasBoardChemicalsStatisRef = ref<InstanceType<typeof gasBoardChemicalsStatis> | null>(null);
// SPC
const gasBoardSPCStatisRef = ref<InstanceType<typeof gasBoardSPCStatis> | null>(null);
// 交接班
const gasBoardShiftTableRef = ref<InstanceType<typeof gasBoardShiftTable> | null>(null);
const topBoardRef = ref<InstanceType<typeof topBoard> | null>(null);

const height = ref<number>(234);

const { height: height_ } = useElementSize(gasOverviewRef);

const statisHeight = computed(() => {
  // return Math.floor((height_.value - 5 * 16 - 66 - 234) / 2 - 32 - 8);
  // return Math.floor(((height_.value - 5 * 16 - 66) * 5) / 14 - 32 - 32 - 6 - 12);
  return Math.floor((height_.value - 5 * 16 - 66 - 234) / 2 - 32 - 32 - 6);
});

// 轮询时间间隔
const carouselDelay = 30000;
const deviceStatisticsTasksRef = ref<InstanceType<typeof deviceStatisticsTasks> | null>(null);
const clock = ref<string>("");
const isShowSafeDays = ref<boolean>(false);
const operationDays = ref<number>(0);
const clickTimer = ref<any>(null);
const carouselTimer = ref<any>(null);
const screenType = ref<Array<boolean>>([true, false, false]);
// 调试
// const screenType = ref<Array<boolean>>([false, false, true]);

const { isFullscreen, toggle } = useFullscreen();
const operationDaysVal = useTransition(operationDays, {
  duration: 1000,
  transition: TransitionPresets.easeInOutExpo
});

// 数据  设备状态 + 今日任务
const deviceStatisticsQueryData = ref<any>(null);
// 数据  气瓶状态统计 + 气瓶更换今日任务 + 酸桶状态统计 + 酸桶更换今日任务 + 侦测器状态统计 + 侦测器隔离今日任务 + 纯水品质 + 大宗气体流量统计 + 槽车填充今日任务 + 质量指标
const platformOverviewQueryData = ref<any>(null);

// 设备状态
const deviceStatisticsRef = ref<InstanceType<typeof echartsChart> | null>(null);
const deviceStatisticsOptions = ref<CommonEcharts.CommonEchartsOption | null>(null);
const deviceStatisticsTitle = ref<string>("设备状态");
// const deviceStatisticsInit = async () => {
//   if (!deviceStatisticsQueryData.value?.deviceStatusStat) return;
//   let keys = Object.keys(deviceStatisticsQueryData.value?.deviceStatusStat);
//   if (!keys?.length) return;
//   keys = keys.filter(key => !!deviceStatusMap.value.get(key));
//   const ec = await deviceStatisticsRef.value?.getEcharts();
//   const data = keys.map(key => {
//     if (!deviceStatusMap.value.get(key)) return null;
//     const value = deviceStatisticsQueryData.value?.deviceStatusStat[key];
//     return value;
//   });
//   const unit = "台";
//   const xAxisData = keys.map(key => deviceStatusMap.value.get(key)?.label || "");
//   const colorList = keys.map(key => deviceStatusMap.value.get(key)?.color || "");
//   const ag = useGetBarChartsAgOptions(xAxisData, data, false, "", colorList, 22);
//   deviceStatisticsOptions.value = useLabelLayoutBarChartFn(ec, xAxisData, data, deviceStatisticsTitle.value, unit, colorList, true, "top", ag);
//   deviceStatisticsRef.value?.loadingInstance?.close();
// };

// 今日告警
const alarmStatRef = ref<InstanceType<typeof echartsChart> | null>(null);
const alarmStatOptions = ref<CommonEcharts.CommonEchartsOption | null>(null);
const alarmStatTitle = ref<string>("今日报警");
// const alarmStatInit = async () => {
//   if (!deviceStatisticsQueryData.value?.alarmStat) return;
//   const {
//     alarmStat: { total = 0, done = 0, undone = 0 }
//   } = deviceStatisticsQueryData.value;
//   const ec = await alarmStatRef.value?.getEcharts();
//   const xAxisData = ["待解决", "已解决", "总报警"];
//   const data = [undone, done, total];
//   const colorList = ["#FFCA45FF", "#00B36DFF", "#FF4355FF"];
//   const ag = useGetBarChartsAgOptions(xAxisData, data, true, "", colorList, 22);
//   alarmStatOptions.value = useLabelLayoutBarChartFn(ec, xAxisData, data, alarmStatTitle.value, "", colorList, false, "", ag);
//   alarmStatRef.value?.loadingInstance?.close();
// };

// 侦测器状态统计
const detectorStatusStatRef = ref<InstanceType<typeof echartsChart> | null>(null);
const detectorStatusStatKey = ref<string>(Math.random().toString(36).slice(2, 10));
const detectorStatusStatOptions = ref<CommonEcharts.CommonEchartsOption | null>(null);
const detectorStatusStatTitle = ref<string>("侦测器状态统计");
const detectorStatusStatInit = async () => {
  detectorStatusStatRef.value.initLoading();
  let metaData = await queryDetectorStatusStat(null, () => {
    detectorStatusStatRef.value?.loadingInstance?.close();
  });
  if (!metaData?.length) return detectorStatusStatRef.value?.loadingInstance?.close();
  const ec = await detectorStatusStatRef.value?.getEcharts();
  const data = metaData
    ?.filter(item => item.name !== "总计")
    ?.map(item => {
      const { name, num: value } = item;
      return { name, value };
    });
  const ag = useGetRingGraphAgOptions(metaData?.find(item => item.name === "总计")?.num, true);
  const colorList = new Map([
    ["报警", "#FF5639"],
    ["离线", "#aaa"],
    ["隔离", "#35CECB"],
    ["运行", "#3B82F6"],
    ["故障", "#FABF2B"],
    ["其它", "#CCB18F"]
  ]);
  const ag_2 = {
    legend: {
      data: Array.from(colorList.keys()),
      orient: "vertical",
      left: "left",
      top: "center"
    }
  };
  // const colorList = ["#3B82F6", "#35CECB", "#FF5639", "#FABF2B", "#FF0066"];
  detectorStatusStatOptions.value = useLabelLayoutRingGraphFn(ec, data, detectorStatusStatTitle.value, "", colorList, { ...ag, ...ag_2 }, true);
  detectorStatusStatRef.value?.loadingInstance?.close();
};

// 侦测器隔离今日任务
const detectorIsolationTasksRef = ref<InstanceType<typeof echartsChart> | null>(null);
const detectorIsolationTasksOptions = ref<CommonEcharts.CommonEchartsOption | null>(null);
const detectorIsolationTasksTitle = ref<string>("侦测器隔离今日任务");
const detectorIsolationTasksTotalData = ref<number>(0);
// const detectorIsolationTasksInit = async () => {
//   detectorIsolationTasksRef.value.initLoading();
//   let data = await queryDetectorIsolationTasks(null, () => {
//     detectorIsolationTasksRef.value?.loadingInstance?.close();
//   });
//   if (!data?.length) return detectorIsolationTasksRef.value?.loadingInstance?.close();
//   const ec = await detectorIsolationTasksRef.value?.getEcharts();
//   const xAxisData = data?.slice(1).map(item => item.name);
//   data = data?.slice(1).map(item => item.num);
//   const colorList = ["#3B82F6", "#FABF2B", "#35CECB", "#FF5639", "#FA8400", "#9755E5", "#355592"];
//   const ag = useGetBarChartsAgOptions(xAxisData, data, true, "", colorList);
//   detectorIsolationTasksOptions.value = useLabelLayoutBarChartFn(
//     ec,
//     xAxisData,
//     data,
//     detectorIsolationTasksTitle.value,
//     "",
//     colorList,
//     false,
//     "",
//     ag
//   );
//   detectorIsolationTasksRef.value?.loadingInstance?.close();
// };

// 酸桶更换今日任务
const acidBucketReplaceTasksRef = ref<InstanceType<typeof echartsChart> | null>(null);
const acidBucketReplaceTasksOptions = ref<CommonEcharts.CommonEchartsOption | null>(null);
const acidBucketReplaceTasksTitle = ref<string>("酸桶更换今日任务");
const acidBucketReplaceTasksTotalData = ref<number>(0);
const acidBucketReplaceTasksInit = async () => {
  acidBucketReplaceTasksRef.value.initLoading();
  let data = await queryAcidBucketTaskStat(null, () => {
    acidBucketReplaceTasksRef.value?.loadingInstance?.close();
  });
  if (!data?.length) return acidBucketReplaceTasksRef.value?.loadingInstance?.close();
  const ec = await acidBucketReplaceTasksRef.value?.getEcharts();
  const xAxisData = data?.slice(1).map(item => item.name);
  data = data?.slice(1).map(item => item.num);
  const colorList = new Map([
    ["已完成", "#48B48F"],
    ["执行中", "#49B0F5"],
    ["未开始", "#FFB266"]
  ]);
  const ag = useGetBarChartsAgOptions(xAxisData, data, true, "", colorList, 22);
  acidBucketReplaceTasksOptions.value = useLabelLayoutBarChartFn(
    ec,
    xAxisData,
    data,
    acidBucketReplaceTasksTitle.value,
    "",
    colorList,
    false,
    "",
    ag
  );
  acidBucketReplaceTasksRef.value?.loadingInstance?.close();
};

// 气瓶状态统计
const gasCylinderStatusStatRef = ref<InstanceType<typeof echartsChart> | null>(null);
const gasCylinderStatusStatOptions = ref<CommonEcharts.CommonEchartsOption | null>(null);
const gasCylinderStatusStatTitle = ref<string>("气瓶状态统计");
const gasCylinderStatusStatInit = async () => {
  gasCylinderStatusStatRef.value.initLoading();
  let metaData = await queryGasCylinderStatusStat(null, () => {
    gasCylinderStatusStatRef.value?.loadingInstance?.close();
  });
  if (!metaData?.length) return gasCylinderStatusStatRef.value?.loadingInstance?.close();
  const ec = await gasCylinderStatusStatRef.value?.getEcharts();
  const data = metaData
    ?.filter(item => item.name !== "总计")
    ?.map(item => {
      const { name, num: value } = item;
      return { name, value };
    });
  const ag = useGetRingGraphAgOptions(metaData?.find(item => item.name === "总计")?.num, true);
  // const colorList = ["#3B82F6", "#FABF2B", "#35CECB", "#FF5639", "#FF0066"];

  const colorList = new Map([
    ["送气中", "#3B82F6"],
    ["吹扫完成", "#35CECB"],
    ["待机中", "#FABF2B"],
    ["下线", "#FF5639"]
  ]);
  const ag_2 = {
    legend: {
      data: Array.from(colorList.keys()),
      orient: "vertical",
      left: "left",
      top: "center"
    }
  };

  gasCylinderStatusStatOptions.value = useLabelLayoutRingGraphFn(ec, data, gasCylinderStatusStatTitle.value, "", colorList, { ...ag, ...ag_2 }, true);
  gasCylinderStatusStatRef.value?.loadingInstance?.close();
};

// 气瓶更换今日任务
const gasCylinderReplaceTasksRef = ref<InstanceType<typeof echartsChart> | null>(null);
const gasCylinderReplaceTasksOptions = ref<CommonEcharts.CommonEchartsOption | null>(null);
const gasCylinderReplaceTasksTitle = ref<string>("气瓶更换今日任务");
const gasCylinderReplaceTasksTotalData = ref<number>(0);
const gasCylinderReplaceTasksInit = async () => {
  gasCylinderReplaceTasksRef.value.initLoading();
  let data = await queryGasCylinderTaskStat(null, () => {
    gasCylinderReplaceTasksRef.value?.loadingInstance?.close();
  });
  if (!data?.length) return gasCylinderReplaceTasksRef.value?.loadingInstance?.close();
  const ec = await gasCylinderReplaceTasksRef.value?.getEcharts();
  const xAxisData = data?.slice(1).map(item => item.name);
  data = data?.slice(1).map(item => item.num);
  const colorList = new Map([
    ["已完成", "#48B48F"],
    ["执行中", "#49B0F5"],
    ["未开始", "#FFB266"]
  ]);
  const ag = useGetBarChartsAgOptions(xAxisData, data, true, "", colorList, 22);
  gasCylinderReplaceTasksOptions.value = useLabelLayoutBarChartFn(
    ec,
    xAxisData,
    data,
    gasCylinderReplaceTasksTitle.value,
    "",
    colorList,
    false,
    "",
    ag
  );
  gasCylinderReplaceTasksRef.value?.loadingInstance?.close();
};

// 槽车填充今日任务
const tankFillingNotifyRef = ref<InstanceType<typeof echartsChart> | null>(null);
const tankFillingNotifyOptions = ref<CommonEcharts.CommonEchartsOption | null>(null);
const tankFillingNotifyTitle = ref<string>("槽车填充今日任务");
const tankFillingNotifyInit = async () => {
  tankFillingNotifyRef.value.initLoading();
  let data = await queryTankTaskStat(null, () => {
    tankFillingNotifyRef.value?.loadingInstance?.close();
  });
  if (!data?.length) return tankFillingNotifyRef.value?.loadingInstance?.close();
  const ec = await tankFillingNotifyRef.value?.getEcharts();
  const xAxisData = data?.slice(1).map(item => item.name);
  data = data?.slice(1).map(item => item.num);
  const colorList = new Map([
    ["已完成", "#48B48F"],
    ["执行中", "#49B0F5"],
    ["未开始", "#FFB266"]
  ]);
  const ag = useGetBarChartsAgOptions(xAxisData, data, true, "", colorList, 22);
  tankFillingNotifyOptions.value = useLabelLayoutBarChartFn(ec, xAxisData, data, tankFillingNotifyTitle.value, "", colorList, false, "", ag);
  tankFillingNotifyRef.value?.loadingInstance?.close();
};

// 酸桶状态统计
const acidBucketStatusStatRef = ref<InstanceType<typeof echartsChart> | null>(null);
const acidBucketStatusStatOptions = ref<CommonEcharts.CommonEchartsOption | null>(null);
const acidBucketStatusStatTitle = ref<string>("酸桶状态统计");
const acidBucketStatusStatInit = async () => {
  acidBucketStatusStatRef.value.initLoading();
  let metaData = await queryAcidBucketStatusStat(null, () => {
    acidBucketStatusStatRef.value?.loadingInstance?.close();
  });
  if (!metaData?.length) return acidBucketStatusStatRef.value?.loadingInstance?.close();
  const ec = await acidBucketStatusStatRef.value?.getEcharts();
  const data = metaData
    ?.filter(item => item.name !== "总计")
    ?.map(item => {
      const { name, num: value } = item;
      return { name, value };
    });
  const ag = useGetRingGraphAgOptions(metaData?.find(item => item.name === "总计")?.num, true);
  const colorList = new Map([
    ["运行", "#3B82F6"],
    ["停止", "#FF5639"]
  ]);
  acidBucketStatusStatOptions.value = useLabelLayoutRingGraphFn(ec, data, acidBucketStatusStatTitle.value, "", colorList, ag, true);
  acidBucketStatusStatRef.value?.loadingInstance?.close();
};

const getEchartsOptions = (data: Record<string, any>) => {
  const { unit = "", valueList = [] } = data;
  const grid = {
    top: 30,
    bottom: 0,
    left: 0,
    right: 0,
    containLabel: true
  };
  const legend = {
    show: true
  };
  const tooltip = {
    show: true,
    trigger: "axis"
  };
  const xAxisData = valueList.map(item => item.name);
  const xAxis = {
    type: "category",
    data: xAxisData
  };
  const yAxis = {
    type: "value",
    name: unit
  };
  const seriesData = valueList.map(item => item.num);
  const series = [
    {
      type: "line",
      data: seriesData
    }
  ];
  return { grid, legend, tooltip, xAxis, yAxis, series };
};

// 大宗气体流量统计
const gasFlowStatEchartsComRef = ref<InstanceType<typeof echartsCom> | null>(null);
const gasFlowStatTypeOptions = ref<Array<any>>([]);
const gasFlowStatEchartsOptions = ref<CommonEcharts.CommonEchartsOption | null>(null);
const gasFlowStatType = ref<string>("");
const gasFlowStatLoading = ref<boolean>(false);
const gasFlowStatEchartsLoading = ref<boolean>(false);
const queryBulkGasConsumptionStatFn = async () => {
  gasFlowStatEchartsLoading.value = true;
  const gasName = gasFlowStatType.value;
  const startDate = dayjs().subtract(7, "day").format("YYYY-MM-DD");
  const endDate = dayjs().format("YYYY-MM-DD");
  const params = { gasName, startDate, endDate };
  const res = await queryBulkGasConsumptionStat(params, () => {
    gasFlowStatEchartsLoading.value = false;
  });
  gasFlowStatEchartsOptions.value = getEchartsOptions(res);
  gasFlowStatEchartsComRef.value.initData(true);
  gasFlowStatEchartsLoading.value = false;
};
const gasFlowStatListInit = async (flag?: boolean) => {
  flag && (gasFlowStatLoading.value = true);
  // gasType  气体类型(BULK_GAS：大宗气，SPECIALTY_GAS：特气，CHEMICAL：化学品
  const res = await queryGasNameList({ gasType: "BULK_GAS" }, () => {
    gasFlowStatLoading.value = false;
  });
  gasFlowStatTypeOptions.value = res;
  gasFlowStatType.value = res[0];
  gasFlowStatLoading.value = false;
  await queryBulkGasConsumptionStatFn();
};

// 化学品用量统计
const chemicalEchartsComRef = ref<InstanceType<typeof echartsCom> | null>(null);
const chemicalTypeOptions = ref<Array<any>>([]);
const chemicalEchartsOptions = ref<CommonEcharts.CommonEchartsOption | null>(null);
const chemicalType = ref<string>("");
const chemicalLoading = ref<boolean>(false);
const chemicalEchartsLoading = ref<boolean>(false);
const queryConsumptionAnalysisFn = async () => {
  chemicalEchartsLoading.value = true;
  const itemKey = chemicalType.value;
  const startDate = dayjs().subtract(7, "day").format("YYYY-MM-DD");
  const endDate = dayjs().format("YYYY-MM-DD");
  const params = { itemKey, startDate, endDate };
  const res = await queryConsumptionAnalysis(params, () => {
    chemicalEchartsLoading.value = false;
  });
  chemicalEchartsOptions.value = getEchartsOptions(res[0]);
  chemicalEchartsComRef.value.initData(true);
  chemicalEchartsLoading.value = false;
};
const chemicalListInit = async (flag?: boolean) => {
  flag && (chemicalLoading.value = true);
  // gasType  气体类型(BULK_GAS：大宗气，SPECIALTY_GAS：特气，CHEMICAL：化学品
  const res = await queryGasNameList({ gasType: "CHEMICAL" }, () => {
    chemicalLoading.value = false;
  });
  chemicalTypeOptions.value = res;
  chemicalType.value = res[0];
  chemicalLoading.value = false;
  await queryConsumptionAnalysisFn();
};

// 质量指标
const spcExceedStatRef = ref<InstanceType<typeof echartsChart> | null>(null);
const spcExceedStatOptions = ref<CommonEcharts.CommonEchartsOption | null>(null);
const spcExceedStatTitle = ref<string>("质量指标");
// const spcExceedStatInit = async () => {
//   spcExceedStatRef.value.initLoading();
//   let data = await querySpcExceedStat(null, () => {
//     spcExceedStatRef.value?.loadingInstance?.close();
//   });
//   if (!data?.length) return spcExceedStatRef.value?.loadingInstance?.close();
//   const ec = await spcExceedStatRef.value?.getEcharts();
//   const xAxisData = data?.map(item => item.name);
//   data = data?.map(item => item.num);
//   const colorList = ["#3B82F6", "#FABF2B", "#35CECB", "#FF5639", "#FA8400", "#9755E5", "#355592"];
//   const ag = useGetBarChartsAgOptions(xAxisData, data, false, "", colorList, 22);
//   ag.yAxis = { show: true };
//   ag.xAxis[0].axisLine = { show: true };
//   ag.xAxis[0].axisTick = { show: true };
//   spcExceedStatOptions.value = useLabelLayoutBarChartFn(ec, xAxisData, data, spcExceedStatTitle.value, "", colorList, false, "", ag);
//   spcExceedStatRef.value?.loadingInstance?.close();
// };

// 获取数据  设备状态 + 今日任务 + 今日告警
// const queryDeviceStatisticsFn = async () => {
//   const params = { classCode: "GAS" };
//   const res = await queryDeviceStatistics(params, () => {
//     deviceStatisticsRef.value?.loadingInstance?.close();
//     alarmStatRef.value?.loadingInstance?.close();
//   });
//   if (res) {
//     deviceStatisticsQueryData.value = res;
//   }
// };

// const initLoading = () => {
//   deviceStatisticsRef.value.initLoading();
//   deviceStatisticsTasksRef.value.initLoading();
//   alarmStatRef.value.initLoading();
// };

const startClock = () => {
  clearClock();
  clickTimer.value = setInterval(async () => {
    clock.value = dayjs().format("YYYY/MM/DD HH:mm:ss");
    const hour = dayjs().get("hour");
    const minute = dayjs().get("minute");
    const second = dayjs().get("second");
    if (hour === 23 && minute === 59 && second === 59) {
      operationDays.value += 1;
      const id = 1;
      const params = { id, num: operationDays.value };
      await updateSafeDays(params);
    }
  }, 1000);
};

const startCarousel = () => {
  clearCarousel();
  carouselTimer.value = setInterval(async () => {
    const index: number = screenType.value.findIndex(item => item);
    screenType.value = screenType.value.map((item, ind, arr) => {
      let nextIndex = null;
      if (index + 1 < arr.length) {
        nextIndex = index + 1;
      } else {
        nextIndex = arr.length - index - 1;
      }
      return nextIndex === ind;
    });
    detectorStatusStatOptions.value = null;
    gasCylinderStatusStatOptions.value = null;
    acidBucketStatusStatOptions.value = null;
    tankFillingNotifyOptions.value = null;
    gasCylinderReplaceTasksOptions.value = null;
    acidBucketReplaceTasksOptions.value = null;
    await nextTick();
    init();
    topBoardRef.value.initAll();
  }, carouselDelay);
};

const clearClock = () => {
  clearInterval(clickTimer.value);
};

const clearCarousel = () => {
  clearInterval(carouselTimer.value);
};

const getSafeDaysFn = async () => {
  const res = await getSafeDays(1);
  if (!res) return;
  const { num } = res;
  operationDays.value = num;
};

const initLoop = async () => {
  const title = "平台概览（气化科）";
  document.title = title;
  startClock();
  startCarousel();
  await getSafeDaysFn();
};

const toFullScreen = () => {
  toggle();
};

const init = async (flag?: boolean) => {
  // flag && initLoading();
  // // 获取数据  设备状态 + 今日任务 + 今日告警
  // queryDeviceStatisticsFn().then(async () => {
  //   // 设备状态
  //   await deviceStatisticsInit();
  //   // 今日任务
  //   await deviceStatisticsTasksRef.value?.init();
  //   deviceStatisticsTasksRef.value?.loadingInstance?.close();
  //   // 今日告警
  //   await alarmStatInit();
  // });
  if (screenType.value[2]) {
    // 侦测器状态统计
    detectorStatusStatInit();
    // 酸桶更换今日任务
    acidBucketReplaceTasksInit();
    // 气瓶状态统计
    gasCylinderStatusStatInit();
    // 气瓶更换今日任务
    gasCylinderReplaceTasksInit();
    // 槽车填充今日任务
    tankFillingNotifyInit();
    // 酸桶状态统计
    acidBucketStatusStatInit();
  }
};

// const initStatusEnum = async () => {
//   const res = await queryDictData({ typeCode: "EQP_RUN_STATUS" });
//   if (!res?.length) return;
//   for (const item of res) {
//     const { name: label = "", value = "" } = item;
//     if (deviceStatus[label]) {
//       deviceStatusMap.value.set(label, { ...item, ...deviceStatus[label], value, label });
//     }
//   }
// };

onMounted(async () => {
  // await initStatusEnum();
  await initLoop();
  init(true);
  // console.log("height   ", height.value);
});

onUnmounted(() => {
  clearClock();
  clearCarousel();
});
</script>

<template>
  <div ref="gasOverviewRef" class="gas-overview">
    <div class="gas-overview-item one">
      <div class="one-item">{{ clock }}</div>
      <div class="one-item one-middle">气化科运维平台概览</div>
      <div class="one-item one-right">
        <div class="one-days" @click="isShowSafeDays = true">安全运行天数：{{ Math.round(operationDaysVal) }}天</div>
      </div>
    </div>

    <!-- 设备状态 -->
    <!-- <div class="gas-overview-item two">
      <echartsChart ref="deviceStatisticsRef" dark :height="height" :title="deviceStatisticsTitle" :options="deviceStatisticsOptions" />
    </div> -->
    <!-- 今日任务 -->
    <!-- <div class="gas-overview-item three">
      <deviceStatisticsTasks ref="deviceStatisticsTasksRef" dark :height="height" :query-data="deviceStatisticsQueryData" />
    </div> -->
    <!-- 今日告警 -->
    <!-- <div class="gas-overview-item four">
      <echartsChart ref="alarmStatRef" dark :title="alarmStatTitle" :options="alarmStatOptions" />
    </div> -->

    <div class="gas-overview-item two">
      <topBoard ref="topBoardRef" class-code="GAS" :height="height" dark />
    </div>

    <!-- 大宗气耗量统计 -->
    <div v-if="screenType[0]" class="gas-overview-item five">
      <gasBoardBulkGasStatis ref="gasBoardBulkGasStatisRef" dark :height="statisHeight" />
    </div>
    <!-- 特气耗量统计 -->
    <div v-if="screenType[0]" class="gas-overview-item six">
      <gasBoardSpecialGasStatis ref="gasBoardSpecialGasStatisRef" dark :height="statisHeight" />
    </div>

    <!-- 化学品耗量统计 -->
    <div v-if="screenType[1]" class="gas-overview-item seven">
      <gasBoardChemicalsStatis ref="gasBoardChemicalsStatisRef" dark :height="statisHeight" />
    </div>
    <!-- SPC -->
    <div v-if="screenType[1]" class="gas-overview-item eight">
      <gasBoardSPCStatis ref="gasBoardSPCStatisRef" dark :height="statisHeight" />
    </div>

    <!-- 侦测器状态统计 -->
    <div v-if="screenType[2]" class="gas-overview-item nine">
      <echartsChart ref="detectorStatusStatRef" dark :height="height" :title="detectorStatusStatTitle" :options="detectorStatusStatOptions" />
    </div>
    <!-- 气瓶状态统计 -->
    <div v-if="screenType[2]" class="gas-overview-item ten">
      <echartsChart
        ref="gasCylinderStatusStatRef"
        dark
        :height="height"
        :title="gasCylinderStatusStatTitle"
        :options="gasCylinderStatusStatOptions"
      />
    </div>
    <!-- 酸桶状态统计 -->
    <div v-if="screenType[2]" class="gas-overview-item eleven">
      <echartsChart ref="acidBucketStatusStatRef" dark :height="height" :title="acidBucketStatusStatTitle" :options="acidBucketStatusStatOptions" />
    </div>
    <!-- 槽车填充今日任务 -->
    <div v-if="screenType[2]" class="gas-overview-item twelve">
      <echartsChart ref="tankFillingNotifyRef" dark :height="height" :title="tankFillingNotifyTitle" :options="tankFillingNotifyOptions" />
    </div>

    <!-- 气瓶更换今日任务 -->
    <div v-if="screenType[2]" class="gas-overview-item thirteen">
      <echartsChart
        ref="gasCylinderReplaceTasksRef"
        dark
        :height="height"
        :title="gasCylinderReplaceTasksTitle"
        :options="gasCylinderReplaceTasksOptions"
      />
    </div>

    <!-- 酸桶更换今日任务 -->
    <div v-if="screenType[2]" class="gas-overview-item fourteen">
      <echartsChart
        ref="acidBucketReplaceTasksRef"
        dark
        :height="height"
        :title="acidBucketReplaceTasksTitle"
        :options="acidBucketReplaceTasksOptions"
      />
    </div>
    <!-- 交接班 -->
    <div v-if="screenType[2]" class="gas-overview-item fifteen">
      <gasBoardShiftTable ref="gasBoardShiftTableRef" dark />
    </div>

    <!-- 侦测器状态统计 -->
    <!-- <div v-if="screenType[0]" class="gas-overview-item five">
      <echartsChart
        ref="detectorStatusStatRef"
        :key="detectorStatusStatKey"
        dark
        :height="height"
        :title="detectorStatusStatTitle"
        :options="detectorStatusStatOptions"
      />
    </div> -->
    <!-- 侦测器隔离今日任务 -->
    <!-- <div v-if="screenType[0]" class="gas-overview-item six">
      <echartsChart
        ref="detectorIsolationTasksRef"
        dark
        :height="height"
        :title="detectorIsolationTasksTitle"
        :options="detectorIsolationTasksOptions"
      />
    </div> -->
    <!-- 酸桶更换今日任务 -->
    <!-- <div v-if="screenType[0]" class="gas-overview-item seven">
      <echartsChart
        ref="acidBucketReplaceTasksRef"
        dark
        :height="height"
        :title="acidBucketReplaceTasksTitle"
        :options="acidBucketReplaceTasksOptions"
      />
    </div> -->

    <!-- 气瓶状态统计 -->
    <!-- <div v-if="screenType[0]" class="gas-overview-item eight">
      <echartsChart
        ref="gasCylinderStatusStatRef"
        dark
        :height="height"
        :title="gasCylinderStatusStatTitle"
        :options="gasCylinderStatusStatOptions"
      />
    </div> -->
    <!-- 气瓶更换今日任务 -->
    <!-- <div v-if="screenType[0]" class="gas-overview-item nine">
      <echartsChart
        ref="gasCylinderReplaceTasksRef"
        dark
        :height="height"
        :title="gasCylinderReplaceTasksTitle"
        :options="gasCylinderReplaceTasksOptions"
      />
    </div> -->
    <!-- 槽车填充今日任务 -->
    <!-- <div v-if="screenType[0]" class="gas-overview-item ten">
      <echartsChart ref="tankFillingNotifyRef" dark :height="height" :title="tankFillingNotifyTitle" :options="tankFillingNotifyOptions" />
    </div> -->

    <!-- 酸桶状态统计 -->
    <!-- <div v-if="screenType[1]" class="gas-overview-item five">
      <echartsChart ref="acidBucketStatusStatRef" dark :height="height" :title="acidBucketStatusStatTitle" :options="acidBucketStatusStatOptions" />
    </div> -->
    <!-- 大宗气体流量统计 -->
    <!-- <div v-if="screenType[1]" class="gas-overview-item six">
      <modelBox title="大宗气体流量统计" dark>
        <div v-loading="gasFlowStatLoading" class="gas-overview-item-line">
          <div class="gas-overview-item-line-select">
            <px-select v-model="gasFlowStatType" @change="queryBulkGasConsumptionStatFn">
              <px-option v-for="item in gasFlowStatTypeOptions" :key="item" :label="item" :value="item" />
            </px-select>
          </div>
          <div v-loading="gasFlowStatEchartsLoading" class="gas-overview-item-line-echarts">
            <echartsCom ref="gasFlowStatEchartsComRef" :options="gasFlowStatEchartsOptions" />
          </div>
        </div>
      </modelBox>
    </div> -->
    <!-- 化学品用量统计 -->
    <!-- <div v-if="screenType[1]" class="gas-overview-item seven">
      <modelBox title="化学品用量统计" dark>
        <div v-loading="chemicalLoading" class="gas-overview-item-line">
          <div class="gas-overview-item-line-select">
            <px-select v-model="chemicalType" @change="queryConsumptionAnalysisFn">
              <px-option v-for="item in chemicalTypeOptions" :key="item" :label="item" :value="item" />
            </px-select>
          </div>
          <div v-loading="chemicalEchartsLoading" class="gas-overview-item-line-echarts">
            <echartsCom ref="chemicalEchartsComRef" :options="chemicalEchartsOptions" />
          </div>
        </div>
      </modelBox>
    </div> -->

    <!-- 质量指标 -->
    <!-- <div v-if="screenType[1]" class="gas-overview-item eight">
      <echartsChart ref="spcExceedStatRef" dark :height="height" :title="spcExceedStatTitle" :options="spcExceedStatOptions" />
    </div> -->

    <div v-if="!isFullscreen" class="full-screen">
      <fullScreen class="icon" @click="toFullScreen" />
    </div>
    <safeDays v-if="isShowSafeDays" v-model="operationDays" v-model:visible="isShowSafeDays" />
  </div>
</template>

<style lang="scss" scoped>
.gas-overview {
  position: relative;
  box-sizing: border-box;
  display: grid;
  grid-template-columns: repeat(24, minmax(16px, 1fr));
  grid-auto-rows: 66px 234px 5fr 5fr;
  grid-auto-flow: column dense;
  grid-gap: 16px;
  width: 100%;
  height: 100%;
  padding: 16px;
  background-color: #001e3bff;

  .gas-overview-item {
    display: flex;
    align-items: center;
    justify-content: center;

    .gas-overview-item-line {
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 100%;

      .gas-overview-item-line-select {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        width: 100%;

        .px-select {
          width: 140px;
        }
      }

      .gas-overview-item-line-echarts {
        flex: 1;
        height: 0;
      }
    }
  }

  .one {
    box-sizing: border-box;
    display: flex;
    grid-column: 1 / 25;
    align-items: center;
    justify-content: space-between;
    height: auto;
    padding: 0 30px;
    background: url("@/assets/images/overview_header.png") no-repeat;
    background-position: center center;
    background-size: 100% 100%;

    .one-item {
      flex: 1;
      font-size: 18px;
      font-weight: 700;
      line-height: 1;
      color: #fff;
      letter-spacing: 4px;
      background: linear-gradient(to top, #00c2ffff, #fff);
      background-clip: text;
      -webkit-text-fill-color: transparent;
    }

    .one-middle {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28px;
    }

    .one-right {
      display: flex;
      align-items: center;
      justify-content: flex-end;

      .one-days {
        &:hover {
          cursor: pointer;
          background: #fff;
          background-clip: text;
          -webkit-text-fill-color: transparent;
        }
      }
    }
  }

  .two {
    // grid-column: 1 / 7;
    grid-column: 1 / 25;
  }

  .three {
    grid-column: 7 / 21;
  }

  .four {
    grid-column: 21 / 25;
  }

  .five {
    grid-column: 1 / 25;
  }

  .six {
    grid-column: 1 / 25;
  }

  .seven {
    grid-column: 1 / 25;
  }

  .eight {
    grid-column: 1 / 25;
  }

  .nine {
    grid-column: 1 / 9;
  }

  .ten {
    grid-column: 9 / 17;
  }

  .eleven {
    grid-column: 17 / 25;
  }

  .twelve {
    grid-column: 1 / 7;
  }

  .thirteen {
    grid-column: 7 / 13;
  }

  .fourteen {
    grid-column: 13 / 19;
  }

  .fifteen {
    grid-column: 19 / 25;
  }

  // .five {
  //   grid-column: 1 / 9;
  // }

  // .six {
  //   grid-column: 9 / 17;
  // }

  // .seven {
  //   grid-column: 17 / 25;
  // }

  // .eight {
  //   grid-column: 1 / 9;
  // }

  // .nine {
  //   grid-column: 9 / 17;
  // }

  // .ten {
  //   grid-column: 17 / 25;
  // }

  // .eleven {
  //   grid-column: 1 / 9;
  // }

  // .twelve {
  //   grid-column: 9 / 17;
  // }

  // .thirteen {
  //   grid-column: 17 / 25;
  // }

  // .fourteen {
  //   grid-column: 1 / 9;
  // }

  // .fourteen {
  //   grid-column: 9 / 17;
  // }

  .full-screen {
    position: absolute;
    top: 6px;
    right: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 36px;
    height: 36px;
    cursor: pointer;
    background-color: var(--px-color-primary-light-9);
    border-radius: 4px;
    box-shadow: 0 0 4px 0 var(--px-color-primary-light-3);

    .icon {
      width: 70%;
      height: 70%;
      color: var(--px-color-primary);
    }

    &:hover {
      background-color: var(--px-color-primary-light-7);
      box-shadow: none;
    }
  }
}

:deep(.px-carousel__indicators--horizontal) {
  height: 14px;
  line-height: 14px;

  .px-carousel__indicator--horizontal {
    padding-bottom: 0;
  }
}
</style>
